package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.production.ErpBomGroup;
import com.nuoniu.sibanyun.mapper.production.ErpBomGroupMapper;
import com.nuoniu.sibanyun.mapper.production.VBomMainMapper;
import com.nuoniu.sibanyun.service.production.IErpBomGroupService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * bom分组 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-07-13
 */
@Service
public class ErpBomGroupServiceImpl extends ServiceImpl<ErpBomGroupMapper, ErpBomGroup> implements IErpBomGroupService {

    @Autowired
    private VBomMainMapper bomMainMapper;

    @Override
    public List<ErpBomGroup> getList() {
        QueryWrapper wrapper = new QueryWrapper();
        UserInfo userInfo = UserThreadLocal.get();
        wrapper.eq("company_id", userInfo.getCompanyId());
        wrapper.orderByAsc("code");
        return list(wrapper);
    }

    @Override
    public void saveBomGroup(ErpBomGroup bomGroup) {
        UserInfo userInfo = UserThreadLocal.get();
        if(bomGroup.getId() == null) {
            bomGroup.setCompanyId(userInfo.getCompanyId());
        }

        ErpBomGroup groupByName = baseMapper.getByName(bomGroup);
        if(groupByName != null && (bomGroup.getId() == null || !bomGroup.getId().equals(groupByName.getId()))) {
            throw new NuoNiuException("名称已存在");
        }

        ErpBomGroup groupByCode = baseMapper.getByCode(bomGroup);
        if(groupByCode != null && (bomGroup.getId() == null || !bomGroup.getId().equals(groupByCode.getId()))) {
            throw new NuoNiuException("编码已存在");
        }

        this.saveOrUpdate(bomGroup);
        bomMainMapper.updateGroupName(bomGroup);
    }

    @Override
    public void deleteById(Long id) {
        Integer count = bomMainMapper.getCountByGroupId(id);
        if(count > 0) {
            throw new NuoNiuException("删除失败,已在物料清单中使用！");
        }

        this.removeById(id);
    }

    @Override
    public void initData(UserInfo userInfo) {
        ErpBomGroup bomGroup = new ErpBomGroup();
        bomGroup.setCode("01");
        bomGroup.setName("默认分组");
        bomGroup.setCompanyId(userInfo.getCompanyId());
        save(bomGroup);
    }
}
